﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.IO;

namespace System.Windows.Media.DirectShow
{
    public static class BinaryExtension
    {


        public static T FillType<T>(this BinaryReader reader)
            where T : new()
        {
            return FillType<T>(reader, Int32.MaxValue);
        }

        public static void WriteType(this BinaryWriter writer, object value)
        {
            foreach (PropertyInfo pi in value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                Type pt = pi.PropertyType;
                object pv = pi.GetValue(value, null);

                if (pt == typeof(Int32))
                    writer.Write((Int32)pv);
                else if (pt == typeof(UInt32))
                    writer.Write((UInt32)pv);
                else if (pt == typeof(UInt16))
                    writer.Write((UInt16)pv);
                else if (pt == typeof(Int16))
                    writer.Write((Int16)pv);
                else if (pt == typeof(FourCC))
                    writer.Write((Int32)pv);
            }
        }

        public static T FillType<T>(this BinaryReader reader, int maxRead)
            where T : new()
        {
            T entity = new T();

            long start = reader.BaseStream.Position;
            foreach (PropertyInfo pi in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (reader.BaseStream.Position - start >= maxRead ) break;

                Type pt = pi.PropertyType;
                object v = null;
                if (pt == typeof(Int32))
                    v = reader.ReadInt32();
                else if (pt == typeof(UInt32))
                    v = reader.ReadUInt32();
                else if (pt == typeof(UInt16))
                    v = reader.ReadUInt16();
                else if (pt == typeof(Int16))
                    v = reader.ReadInt16();
                else if (pt == typeof(FourCC))
                    v = (FourCC)reader.ReadInt32();

                if (v != null)
                    pi.SetValue(entity, v, null);
            }

            return entity;
        }
    }
}
